package com.csw.android.androidtest.module.servive;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.csw.android.androidtest.RemoteServiceAIDLInterface;
import com.csw.android.androidtest.app.MyApplication;
import com.csw.android.androidtest.service.RemoteService;
import com.csw.android.androidtest.ui.LogViewFragment;

/**
 * 远程服务，服务作为android四大组件之一，当然也可以运行在别的进程，当服务运行在别的进程，就需要跨进程通信了。
 * 一般可以使用startService或者startForegroundService,联合广播实现跨进程通信。这里我们使用另外一个机制，
 * 使用BindService+AIDL实现跨进程通信
 */
public class RemoteServiceTest extends LogViewFragment {

    private RemoteServiceAIDLInterface bindServiceInstance = null;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bindServiceInstance = RemoteServiceAIDLInterface.Stub.asInterface(service);
            //这里可以看出，虽然可以同步调用，但有可能会抛出远程异常，所以代码看着也是有点蛋疼啊
            try {
                logView.addLog(bindServiceInstance.execCommand1("12345"));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                logView.addLog(bindServiceInstance.execCommand2());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bindServiceInstance = null;
        }
    };

    @Override
    public void initData() {
        super.initData();
        MyApplication.instance.bindService(new Intent(MyApplication.instance, RemoteService.class), serviceConnection, Service.BIND_AUTO_CREATE);
    }

    @Override
    public void onDestroy() {
        MyApplication.instance.unbindService(serviceConnection);
        super.onDestroy();
    }

}
